package cn.itcast.account.service.impl;

import cn.itcast.account.entity.AccountFreeze;
import cn.itcast.account.mapper.AccountFreezeMapper;
import cn.itcast.account.mapper.AccountMapper;
import cn.itcast.account.service.AccountTCCService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class AccountTCCServiceImpl implements AccountTCCService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private AccountFreezeMapper accountFreezeMapper;

    @Override
    @Transactional
    public void deduct(String userId, int money) {

        //0.获取事务id
        String xid = RootContext.getXID();
        //判断是否业务悬挂
        AccountFreeze freezeOld = accountFreezeMapper.selectById(xid);
        if (freezeOld!=null){
            //已经cancel过了，拒绝处理
            return;
        }

        //1.扣减可用金额
        accountMapper.deduct(userId, money);
        //2.记录冻结金额，事务状态
        AccountFreeze freeze=new AccountFreeze();
        freeze.setUserId(userId);
        freeze.setFreezeMoney(money);
        freeze.setState(AccountFreeze.State.TRY);
        freeze.setXid(xid);
        accountFreezeMapper.insert(freeze);

    }

    @Override
    public boolean confirm(BusinessActionContext ctx) {
        //获取事务id  BusinessActionContext里面自带事务id值
        String xid = ctx.getXid();
        //删除冻结记录
        int count = accountFreezeMapper.deleteById(xid);
        return count==1;
    }

    @Override
    @Transactional
    public boolean cancel(BusinessActionContext ctx) {

        //查询冻结记录
        String xid = ctx.getXid();
        AccountFreeze freeze = accountFreezeMapper.selectById(xid);
        //空回滚判断
        if (freeze==null){
            freeze=new AccountFreeze();
            freeze.setUserId(ctx.getActionContext("userId").toString());
            freeze.setFreezeMoney(0);
            freeze.setState(AccountFreeze.State.CANCEL);
            freeze.setXid(xid);
            accountFreezeMapper.insert(freeze);
            return true;
        }
        //幂等处理 让因为网络不稳定，导致多次执行方法的数据依然不出错。
        if (freeze.getState()==AccountFreeze.State.CANCEL){
           return true;
        }


        //恢复可用余额
        accountMapper.refund(freeze.getUserId(),freeze.getFreezeMoney());
        //将冻结金额清0，且状态改为cancel
        freeze.setFreezeMoney(0);
        freeze.setState(AccountFreeze.State.CANCEL);
        int count = accountFreezeMapper.updateById(freeze);

        return count==1;
    }
}
